<template>
	<view class="store-info">
		<view class="card" id="scrollFlag">
			<view class="title">
				门店信息
			</view>
			<u-form class="form" labelPosition="left" :model="formData" :rules="rules" ref="formRef">
				<u-form-item class="form-item" label="半径配送距离（KM）" labelWidth="150">
					<u-input border="bottom" :clearable="true" v-model="formData.shop_info.delivery_distance"
						placeholder="请输入半径配送距离"></u-input>
				</u-form-item>

				<u-form-item class="form-item" label="营业时间" labelWidth="100">
					<view class="choose-time">
						<picker mode="time" :value="formData.shop_info.business_hours_start" start="08:00" end="21:00"
							@change="bindTimeChange($event, 1)">
							<view class="uni-input">{{formData.shop_info.business_hours_start}}</view>
						</picker>
						至
						<picker mode="time" :value="formData.shop_info.business_hours_end" start="08:00" end="21:00"
							@change="bindTimeChange($event, 2)">
							<view class="uni-input">{{formData.shop_info.business_hours_end}}</view>
						</picker>
					</view>
				</u-form-item>

				<u-form-item class="form-item" label="营业日" labelWidth="100">
					<u-checkbox-group v-model="business_weeks" @change="changeBusinessWeek">
						<u-checkbox :customStyle="{marginBottom: '8px'}" shape="circle" :disabled="item.disabled"
							v-for="(item, index) in businessWeekList" :key="index" :name="item.value"
							:label="item.name">
						</u-checkbox>
					</u-checkbox-group>
				</u-form-item>

				<u-form-item class="form-item" label="营业状态" labelWidth="100" v-if="formData.opt_type!='improve'">
					<u-radio-group v-model="formData.shop_info.business_status" @change="businessStatusChange">
						<u-radio v-for="(item,index) in businessStatusList" :key="index" :name="item.value"
							:label="item.name" :disabled="item.disabled"></u-radio>
					</u-radio-group>
				</u-form-item>

				<view class="addreaa">
					<view class="title">
						地址信息
					</view>
					<u-form-item class="form-item" label="经营地区" labelWidth="100">
						<uni-data-picker v-model="formData.address_info.area_code" :localdata="areaList"
							popup-title="请选择经营地区" @change="areaConfirm"></uni-data-picker>
					</u-form-item>
					<!-- #ifdef MP || APP -->
					<u-form-item class="form-item" label="详细地址" labelWidth="100" @click="selectAdress()">
						<u-textarea border="bottom" :clearable="true" v-model="formData.address_info.street_address"
							placeholder="请选择精确地址"></u-textarea>
						<uni-icons slot="right" name="arrow-right"></uni-icons>
					</u-form-item>
					<!-- #endif -->
					<!-- #ifdef H5 -->
					<u-form-item class="form-item" label="详细地址" labelWidth="100">
						<u-textarea border="bottom" :clearable="true" v-model="formData.address_info.street_address"
							placeholder="请输入详细地址"></u-textarea>
					</u-form-item>
					<!-- #endif -->
				</view>

				<view class="license store">
					<view class="name">
						店铺照片
					</view>
					<view class="upload">
						<uni-file-picker v-model="frontList" file-mediatype="image" mode="grid"
							:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn
							:limit="1" @select="selectFile($event, 1)" @delete="removeOk($event, 1)">
							<view class="custom-upload" slot="addBtn">
								<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
								<text class="label">门头照片</text>
							</view>
						</uni-file-picker>
						<view class="example-img" @click="previewImg(imgHost+'/static/images/example/store-head.png')">
							<image mode="withFix" width="100%" height="100%"
								:src="imgHost+'/static/images/example/store-head.png'"></image>
							<view class="label">门头照片示例图</view>
						</view>
					</view>
					<view class="upload">
						<uni-file-picker v-model="cashList" file-mediatype="image" mode="grid"
							:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn
							:limit="1" @select="selectFile($event, 2)" @delete="removeOk($event, 2)">
							<view class="custom-upload" slot="addBtn">
								<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
								<text class="label">收银台</text>
							</view>
						</uni-file-picker>
						<view class="example-img" @click="previewImg(imgHost+'/static/images/example/pay.png')">
							<image mode="withFix" width="100%" height="100%"
								:src="imgHost+'/static/images/example/pay.png'"></image>
							<view class="label">收银台示例图</view>
						</view>
					</view>
					<view class="upload">
						<uni-file-picker v-model="envList" file-mediatype="image" mode="grid"
							:image-styles="imageStyles" :file-extname="extname" :auto-upload="false" custom-btn
							:limit="1" @select="selectFile($event, 3)" @delete="removeOk($event, 3)">
							<view class="custom-upload" slot="addBtn">
								<uni-icons type="camera-filled" size="52" color="#999"></uni-icons>
								<text class="label">店内环境</text>
							</view>
						</uni-file-picker>
						<view class="example-img" @click="previewImg(imgHost+'/static/images/example/env.png')">
							<image mode="withFix" width="100%" height="100%"
								:src="imgHost+'/static/images/example/env.png'"></image>
							<view class="label">店内环境例图</view>
						</view>
					</view>
				</view>
			</u-form>
		</view>

		<view class="opt-btn">
			<view><button type="success" @click="stepHandle(backStep, 'back')">上一步</button></view>
			<view><button type="primary" @click="stepHandle(nextStep, 'next')">提交</button></view>
		</view>
	</view>
</template>

<script setup>
	import request from '@/utils/request';
	import cache from '@/utils/cache';
	import util from '@/utils/util';
	import {
		onMounted,
		reactive,
		toRefs,
		defineProps,
		ref
	} from 'vue';

	defineOptions({
		name: 'store-info'
	});

	onMounted(() => {
		console.log('组件已挂载');
		// 这里可以执行需要在DOM挂载后执行的代码
		initData();
	});

	const props = defineProps({
		backStep: 2,
		nextStep: 4,
		formData: {
			type: Object,
			default () {
				return {
					// 店铺信息
					shop_info: {
						store_logo: '', //Logo
						store_front_photo: "", // M 门头照 
						store_cash_photo: "", // M 收银台照片 
						store_env_photo: "", //M 经营场所内设照片
						delivery_distance: 10, // 配送距离
						business_hours_start: "09:00", // 开始营业时间
						business_hours_end: "18:00", // 结束营业时间
						business_status: 0, // 营业状态
						business_week: '1,2,3,4,5,6,7', //营业日
					},

					// 店铺地址信息
					address_info: {
						province_code: "0", // M商户所在省
						city_code: "0", // M 商户所在市
						area_code: "0", // M 商户所在区
						store_area_str: "", // 显示选择地名
						street_address: "", // M 商户详细地址
						longitude: "0.000000", // M 门店地址经度
						latitude: "0.000000", // M 门店地址纬度
					},
				}
			}
		}
	});

	const state = reactive({
		themeColor: cache.get('themeColor'),
		imgHost: util.requestUrl(),

		frontList: [],
		cashList: [],
		envList: [],

		areaList: [], // 地区列表

		businessStatusList: [{
			value: 0,
			name: '休息中',
			disabled: false,
		}, {
			value: 1,
			name: '营业中',
			disabled: false,
		}],
		businessWeekList: [{
			value: 1,
			name: '周一',
			disabled: false,
		}, {
			value: 2,
			name: '周二',
			disabled: false,
		}, {
			value: 3,
			name: '周三',
			disabled: false,
		}, {
			value: 4,
			name: '周四',
			disabled: false,
		}, {
			value: 5,
			name: '周五',
			disabled: false,
		}, {
			value: 6,
			name: '周六',
			disabled: false,
		}, {
			value: 7,
			name: '周日',
			disabled: false,
		}],

		isOK: false,
	});

	const rules = ref([]);
	const formRef = ref();
	const extname = ref('jpg,jpeg,png,bmp,gif,tif,svg,webp');
	const imageStyles = ref({
		"width": '316rpx', // 边框宽度
		"height": '260rpx', // 边框高度
		"border": { // 如果为 Boolean 值，可以控制边框显示与否
			"color": "#909193", // 边框颜色
			"width": "1px", // 边框宽度
			"style": "solid", // 边框样式
		}
	});
	const business_weeks = ref([1, 2, 3, 4, 5, 6, 7]);
	const emits = defineEmits(["changeStep", "update:formData"]);

	// 下一步
	function stepHandle(step, type) {
		if (type == 'back') {
			console.log('上一步', step);
			emits('changeStep', step);
		} else {
			let check = checkData();
			if (!check) {
				return;
			}
			resolveAddress();
			setTimeout(() => {
				if (state.isOK) {
					console.log('下一步', step);
					emits('changeStep', step);
				}
			}, 800);
		}
	}

	function resolveAddress() {
		request.get('amap/geo', {
			address: props.formData.address_info.street_address
		}).then(res => {
			console.log('解析信息', res);
			if (res.code == 1) {
				const areaCode = res.data.areaCode;
				props.formData.address_info.longitude = res.data.longitude;
				props.formData.address_info.latitude = res.data.latitude;
				props.formData.address_info.store_area_str = res.data.areaStr;
				props.formData.address_info.province_code = areaCode.substr(0, 2);
				props.formData.address_info.city_code = areaCode.substr(0, 4);
				props.formData.address_info.area_code = areaCode.substr(0, 6);
				console.log(props.formData.address_info);
				state.isOK = true;
				emits('update:formData', props.formData);
			}
		})
	}

	function checkData() {
		if (!props.formData.shop_info.delivery_distance) {
			util.showTip('请填写半径配送距离');
			return false;
		}
		if (business_weeks.value.length == 0) {
			util.showTip('请选择营业日');
			return false;
		}
		if (!props.formData.address_info.street_address) {
			util.showTip('请填写详细地址');
			return false;
		}
		if (!props.formData.shop_info.store_front_photo) {
			util.showTip('请上传门头照');
			return false;
		}
		if (!props.formData.shop_info.store_cash_photo) {
			util.showTip('请上传收银台照片');
			return false;
		}
		if (!props.formData.shop_info.store_env_photo) {
			util.showTip('请上传店内环境照片');
			return false;
		}
		return true;
	}

	// 选择营业时间
	function bindTimeChange(e, flag) {
		console.log('picker发送选择改变，携带值为', e, flag);
		if (flag == 1) {
			props.formData.shop_info.business_hours_start = e.detail.value;
		}
		if (flag == 2) {
			props.formData.shop_info.business_hours_end = e.detail.value;
		}
		console.log('营业时间：' + props.formData.shop_info.business_hours_start + '至' + props.formData.shop_info
			.business_hours_end);
	}

	// 初始化数据
	function initData() {
		// 门店
		if (props.formData.shop_info.store_front_photo) {
			state.frontList = [{
				name: props.formData.shop_info.store_front_photo,
				extname: 'image', // 文件类型，image/video/file
				url: state.imgHost + props.formData.shop_info.store_front_photo,
			}];
		}

		// 收银台
		if (props.formData.shop_info.store_cash_photo) {
			state.cashList = [{
				name: props.formData.shop_info.store_cash_photo,
				extname: 'image',
				url: state.imgHost + props.formData.shop_info.store_cash_photo,
			}]
		}

		// 店内
		if (props.formData.shop_info.store_env_photo) {
			state.envList = [{
				name: props.formData.shop_info.store_env_photo,
				extname: 'image',
				url: state.imgHost + props.formData.shop_info.store_env_photo,
			}];
		}

		// 营业日
		const selectedWeeks = props.formData.shop_info.business_weeks;
		if (selectedWeeks) {
			let weeks = []
			selectedWeeks.forEach(item => {
				weeks.push(parseInt(item));
			})
			business_weeks.value = weeks;
		}

		getCity();
	}

	// 选择精确地址
	function selectAdress() {
		console.log('打开地图选择位置');
		uni.chooseLocation({
			success: function(res) {
				console.log('选择位置', res);
				props.formData.address_info.street_address = res.address;
				props.formData.address_info.longitude = res.longitude;
				props.formData.address_info.latitude = res.latitude;
				state.isOK = true;
				emits('update:formData', props.formData);
			},
			fail: (error) => {
				console.error('地图选择异常', error);
			}
		})
	}

	// 获取省市区县编码
	function getCity() {
		let city = cache.get("shop_getCity");
		if (city) {
			state.areaList = city;
			return;
		}

		request.get("address/getThreeArea", {})
			.then(res => {
				state.areaList = res.data;
				cache.set('shop_getCity', res.data);
			})
			.catch(err => {
				console.log('获取数据异常', err);
			})
	}

	// 确认选择地区
	function areaConfirm(res) {
		console.log('确认选择地区', res);
		const data = res.detail.value;
		let areaStr = data[0].text + '-' + data[1].text + '-' + data[2].text;
		props.formData.address_info.store_area_str = areaStr;
		// 省，市，县编码
		props.formData.address_info.province_code = data[0].value;
		props.formData.address_info.city_code = data[1].value;
		props.formData.address_info.area_code = data[2].value;
		emits('update:formData', props.formData);
	}

	// 选择图片
	function selectFile(res, flag) {
		console.log('selectFile', res, flag);

		// 上传
		for (let i = 0; i < res.tempFilePaths.length; i++) {
			upload(res.tempFilePaths[i], flag);
		}
	}

	// 删除照片
	function removeOk(res, flag) {
		console.log('removeOk', res, flag);
		if (flag == 1) {
			props.formData.shop_info.store_front_photo = "";
			state.frontList = [];
		}
		if (flag == 2) {
			props.formData.shop_info.store_cash_photo = "";
			state.cashList = [];
		}
		if (flag == 3) {
			props.formData.shop_info.store_env_photo = "";
			state.envList = [];
		}
	}

	// 图片上传
	function upload(file, flag) {
		let type = "store";
		uni.uploadFile({
			url: util.requestUrl() + '/api/upload/uploadfile', // 开发者服务器接口地址
			filePath: file, // 要上传文件资源的路径
			name: 'file', // 文件对应的 key
			formData: {
				'type': type,
				'token': cache.get('M_LOGIN_TOKEN', false) || '',
				'role': cache.get('role', false) || 0,
			}, // 请求的 form data
			success: (res) => {
				const json = JSON.parse(res.data);
				if (json.code == 1) {
					const data = json.data;
					console.log('上传成功', data);
					util.showTip(data.originalName + '上传成功');
					// 处理上传成功的结果
					if (flag == 1) {
						props.formData.shop_info.store_front_photo = data.url;
						state.frontList = [{
							name: data.url,
							extname: data.fileType, // 文件类型，image/video/file
							url: data.url2,
						}];
					}

					if (flag == 2) {
						props.formData.shop_info.store_cash_photo = data.url;
						state.cashList = [{
							name: data.url,
							extname: data.fileType,
							url: data.url2,
						}];
					}

					if (flag == 3) {
						props.formData.shop_info.store_env_photo = data.url;
						state.envList = [{
							name: data.url,
							extname: data.fileType,
							url: data.url2,
						}];
					}
					emits('update:formData', props.formData);
				}
			},
			fail: (error) => {
				console.error('上传失败', error);
				// 处理上传失败的错误
				uni.showToast({
					title: '网络错误，请稍后再试！',
					icon: fail,
					duration: 2000
				})
			}
		});
	}

	function changeBusinessWeek(e) {
		console.log('营业日', e);
	}

	function businessStatusChange(e) {
		console.log('营业状态', e);
	}

	// 图片预览
	function previewImg(url) {
		uni.previewImage({
			urls: [url]
		})
	}

	function pageRoute(url) {
		uni.navigateTo({
			url
		});
	};

	function pageTabRoute(url) {
		uni.reLaunch({
			url
		});
	};

	const {
		themeColor,
		imgHost,
		frontList,
		cashList,
		envList,
		areaList,
		businessStatusList,
		businessWeekList,
		isOK,
	} = toRefs(state);
</script>

<style lang="scss">
	.store-info {
		.card {
			margin: 24rpx 0;
			padding: 0 24rpx 24rpx;
			background-color: #fff;
			border-radius: 16rpx;

			.title {
				display: flex;
				align-items: center;
				height: 90rpx;
				font-size: $font-32;
				color: #303133;
			}

			.license,
			.m-identify,
			.identify {
				.name {
					@include f-between;
					height: 80rpx;
					color: #303133;
					line-height: 80rpx;

					.more {
						@include f-center;
						font-size: $font-24;
						color: #909193
					}
				}
			}

			.tips {
				@include f-between;
				padding: 24rpx 0;
				border-bottom: 1rpx solid #dadbde;

				.desc {
					flex: 1;
					margin-left: 8rpx;
					color: #ffc30f;
					font-size: $font-20;
				}

				.more {
					@include f-center;
					font-size: $font-20;
					color: #909193;
				}
			}

			.choose-time {
				display: flex;
				align-items: center;
				padding: 20rpx 0 24rpx;
				border-bottom: 1rpx solid #dadbde;

				.uni-input,
				input {
					width: 200rpx;
					text-align: center;
					font-size: $font-26;
				}
			}
		}

		.upload {
			@include f-between;

			.u-list-item {
				margin: 0;
			}

			.custom-upload,
			.example-img {
				overflow: hidden;
				width: 316rpx;
				height: 260rpx;
				background-color: #f3f4f6;
				border-radius: 12rpx;
			}

			.custom-upload {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.label {
					margin-top: 12rpx;
					font-size: $font-26;
					color: #909193;
				}
			}

			.example-img {
				position: relative;

				.label {
					@include f-center;
					position: absolute;
					bottom: 0;
					left: 0;
					width: 100%;
					height: 60rpx;
					background-color: rgba(0, 0, 0, 0.5);
					color: #fff;
					font-size: $font-26;
				}
			}
		}

		.store {
			.upload {
				margin-top: 24rpx;
			}
		}

		.opt-btn {
			display: flex;
			flex-direction: row;
			justify-content: space-around
		}
	}
</style>